<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas手势</title>

  <style>
    #app {
      border: 2px blue dashed;
      position: absolute;
      left: 20px;
      top: 10px;
    }

    .btn {
      position: absolute;
      left: 22px;
      top: 12px;
    }
  </style>
</head>

<body>
  <canvas id="app" width="500" height="500"></canvas>
  <button onclick="clearCanvas()" class="btn">清除</button>

  <script>
    const cvs = document.getElementById('app');
    const ctx = getCanvasContext2D()
    //ctx.strokeStyle = 'rgba(255,0,0,1)'
    
    ctx.lineWidth = 5
    ctx.lineCap = 'round'
    ctx.lineJoin = 'round'

    const MIN_LENGTH = 20
    let rightDrawing = false
    let lastX = 0
    let lastY = 0

    cvs.addEventListener('contextmenu', e => {
      e.preventDefault()
    })

    cvs.addEventListener('mousedown', e => {
      if (e.button != 2) return // 2为右键
      rightDrawing = true
      ctx.strokeStyle = getRandomRGB()
      ctx.beginPath()
      ctx.moveTo(e.clientX - cvs.offsetLeft, e.clientY - cvs.offsetTop)
    })

    cvs.addEventListener('mousemove', e => {
      if (!rightDrawing) return
      ctx.lineTo(e.clientX - cvs.offsetLeft, e.clientY - cvs.offsetTop)
      ctx.closePath()
      ctx.stroke()

      //ctx.strokeStyle = getRandomRGB()
      ctx.beginPath()
      ctx.moveTo(e.clientX - cvs.offsetLeft, e.clientY - cvs.offsetTop)
    })

    cvs.addEventListener('mouseup', e => {
      rightDrawing = false
    })

    /**
     * 获取canvas上下文对象2D版本，此处加入jsdoc以便可以获得vscode的代码提示
     * @return {CanvasRenderingContext2D}
     */
    function getCanvasContext2D() {
      return cvs.getContext('2d')
    }

    //////////////////////
    function clearCanvas() {
      ctx.clearRect(0, 0, cvs.width, cvs.height)
    }

    function getRandomRGB(){
      const r = Math.random() * 155 + 100
      const g = Math.random() * 155 + 100
      const b = Math.random() * 155 + 100
      return `rgb(${r}, ${g}, ${b})`
    }

    function getX(){
      
    }
  </script>
</body>

</html>